package cn.wind.xboot.core.utils;

import cn.wind.xboot.core.constant.ApiConstant;
import com.google.common.collect.Maps;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xukk
 * @date 2018/5/4.
 */
public class PasswordUtil {
    private static BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    public static Boolean matches(String rawPassword, String... encodePassword) {
        Map<String, Boolean> map = Maps.newHashMap();
        map.put("flag", false);
        Arrays.asList(encodePassword).forEach(v -> {
            if (encoder.matches(rawPassword, v)) {
                map.put("flag", true);
            }
        });
        return map.get("flag");
    }
    public static String encode(String rawPassword) {
        return encoder.encode(rawPassword.trim());
    }

    public static boolean checkPwdFormat(String psw,String pattern)
    {
        if(psw == null || psw.isEmpty()){
            return false;
        }
        // 密码验证的正则表达式:由数字和字母组成，并且要同时含有数字和字母，且长度要在8-16位之间。
        String regex = pattern==null? ApiConstant.STRONG_PASSWORD:pattern;
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(psw);
        return m.matches();
    }

    public static Integer checkPwd(String psw){
        if(psw.length()>16||psw.length()<8){
            return -1;
        }
        if(checkPwdFormat(psw,ApiConstant.STRONG_PASSWORD)){
            return 3;
        }
        if(checkPwdFormat(psw,ApiConstant.MIDDLE_PASSWORD)){
            return 2;
        }
        if(checkPwdFormat(psw,ApiConstant.SICK_PASSWORD)){
            return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
        System.out.println(checkPwdFormat("xukk123",ApiConstant.MIDDLE_PASSWORD));
    }
}
